package com.ynet.middleground.approve.listener;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.el.FixedValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.ynet.middleground.approve.cmd.SpringContextUtils;
import com.ynet.middleground.approve.constant.WorkflowConstants;

/**
 * @author liulx
 * @description 任务节点添加提醒信息
 * @date 2020-06-15 15:48
 */
@DependsOn("springContextUtils")
@Service
public class TaskTipsListener extends BaseListener implements TaskListener {

    protected TaskService taskService = SpringContextUtils.getBean(TaskService.class);

    /**
     * 获取配置的业务属性 code 列表（以英文逗号隔开）
     */
    private FixedValue codeValue;

    @Override
    public void notify(DelegateTask delegateTask) {
        if (codeValue != null) {
            String codeString = codeValue.getExpressionText();
            if (StringUtils.isNotBlank(codeString)) {
                // 以英文逗号分隔，拆分成集合，并以此存入当前任务变量集合中
                List<String> codeList = Arrays.stream(codeString.split(",")).collect(Collectors.toList());
                Map<String, Object> variables = delegateTask.getVariablesLocal();
                variables = Optional.ofNullable(variables).orElse(Maps.newHashMap());
                for (String code : codeList) {
                    variables.put(code, true);
                }
                taskService.setVariablesLocal(delegateTask.getId(), variables);
                taskService.setVariableLocal(delegateTask.getId(), WorkflowConstants.FLOW_BUSINESS_OPERATE_DATA,
                    variables);
            }
        }

    }
}
